import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import {Link, useSearchParams} from 'react-router-dom'
import './index.scss'
import RichTextEditor from "./components/RichTextEditor.jsx";
import {useEffect, useState} from "react";
import {getArticleDetailAPI, submitArticleAPI, updateArticleAPI, uploadImageAPI} from "../../apis/article.jsx";
import {useChannel} from "../../hooks/useChannel.jsx";

const { Option } = Select

const Publish = () => {
   const { channelList} = useChannel()

    const onFinish = async (values) => {
        const { channel_id, richText, title, coverURL } = values
        // 富文本转字符串
        const content = JSON.stringify(richText)
        // 准备请求数据
        const reqData = {
            draft : true,
            title : title,
            content : content,
            coverType : imageType,
            coverURL : coverURL.join(','),
            channelID : channel_id
        }
        console.log("reqData:", reqData)

        if (articleId) {
            updateArticleAPI(articleId ,reqData)
        }else {
            submitArticleAPI(reqData)
        }

    }
    const [form] = Form.useForm();
    const onChange = () => {
        console.log("正在上传中", )
    }

    const [imageType, setImageType] = useState(0)
    const [coverURL, setCoverURL] = useState([])
    const onTypeChange = (e) => {
        setImageType(e.target.value)
    }

    // 封装上传处理函数
    const handleUpload = async ({ file, onSuccess, onError }) => {
        try {
            const res = await uploadImageAPI(file);
            onSuccess(res.data); // 通知Upload组件上传成功
            const currentUrls = form.getFieldValue('coverURL') || [];
            const newUrls =  [...currentUrls, res.data.url];
            // 将返回的图片URL存入表单（根据实际接口结构调整）
            form.setFieldsValue({ coverURL: newUrls });
            setCoverURL(newUrls);
        } catch (error) {
            onError(error); // 通知Upload组件上传失败
            if (error.response && error.response.status === 400) {
                console.error('上传失败:', error.response.data);
            } else {
                console.error('其他错误:', error);
            }
        }
    };

    // 回填查询得到的文章数据
    const [searchParams] = useSearchParams();
    const articleId = searchParams.get('id')
    useEffect(() => {
          async function getArticleDetail(){
              const res = await getArticleDetailAPI(articleId)
              const article = res.data.Article;
              const cover = res.data.Cover;
              const coverURLs = cover.image_url ? cover.image_url.split(',') : [];
              console.log("getArticleDetailAPI:", res)
              form.setFieldsValue({
                  title: article.title, // 标题
                  richText: JSON.parse(article.content), // 富文本内容
                  channel_id: article.channel_id, // 频道 ID
                  coverURL: coverURLs, // 封面 URL
                  type: cover.type, // 封面类型
              })
              setImageType(cover.type)
              setCoverURL(coverURLs)
          }
          if (!articleId) return
          getArticleDetail()
        },[articleId, form]
    );

    return (
        <div className="publish">
            <Card
                title={
                    <Breadcrumb items={[
                        { title: <Link to={'/'}>首页</Link> },
                        { title: `${articleId ? '编辑' : '发布'}文章 `  },
                    ]}
                    />
                }
            >
                <Form
                    form={form}
                    onFinish={onFinish}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{
                        type: 0 ,
                        coverURL : [],
                        richText : [
                            {
                                type: 'paragraph',
                                children: [{ text: '开始输入你的文本...' }],
                            },
                        ]}}
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: '请输入文章标题' }]}
                    >
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item
                        label="频道"
                        name="channel_id"
                        rules={[{ required: true, message: '请选择文章频道' }]}
                    >
                        <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                            {channelList.map(item => <Option key={item.ID} value={item.ID}>{item.name}</Option>)}
                        </Select>
                    </Form.Item>
                    <Form.Item label="封面">
                        <Form.Item name="type">
                            <Radio.Group onChange={onTypeChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item name="coverURL" hidden preserve>
                            <Input />
                        </Form.Item>
                        {imageType > 0 && <Upload
                            listType="picture-card"
                            showUploadList
                            name = "image"
                            onChange={onChange}
                            customRequest={handleUpload}
                            maxCount={imageType}
                            fileList={coverURL.map(url => ({ url }))}
                        >
                            <div style={{ marginTop: 8 }}>
                                <PlusOutlined />
                            </div>
                        </Upload>}

                    </Form.Item>
                    <Form.Item
                        label="内容"
                        name="richText"
                        rules={[{ required: true, message: '请输入文章内容' }]}
                    >
                        <RichTextEditor
                            key={form.getFieldValue('richText')}
                            value={form.getFieldValue('richText')}
                            onChange={(newValue)=> {form.setFieldValue('richText',  JSON.parse(JSON.stringify(newValue)))}}/>
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button size="large" type="primary" htmlType="submit">
                                发布文章
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}

export default Publish